﻿using JNPF.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARK.Common.WxPayAPIS;
using PARK.Consumer;
using PARK.Consumer.Interfaces.WechatRecharge;
using PARK.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using WeChat.Api.Common;
using WeChat.Api.Model.CreateOrder;

namespace PARK.API
{
    /// <summary>
    ///  微信支付回调
    /// </summary>
    [Route("api/wechat/[controller]")]
    public class WxPayController : Controller
    {
        private readonly IWechatRechargeService _WechatRechargeService; 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="wechatRechargeService"></param>
        public WxPayController(
            IWechatRechargeService wechatRechargeService)
        {
            _WechatRechargeService = wechatRechargeService;
        }

        #region 微信支付回调通知
        /// <summary>
        /// 微信支付回调通知
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("PayNotify")]
        [AllowAnonymous]
        public async Task<string> PayNotify()
        {
            new LoggEx().Info("微信支付->收到支付通知1...");
            try
            {
                //获取回调POST过来的xml数据的代码
                Stream stream = HttpContext.Request.Body;
                byte[] buffer = new byte[HttpContext.Request.ContentLength.Value];
                await stream.ReadAsync(buffer, 0, buffer.Length); //.net core 3.1需要用ReadAsync才不会出错
                string xml = Encoding.UTF8.GetString(buffer);
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(xml);
                XmlNode root = xdoc.SelectSingleNode("xml");
                XmlNodeList xnl = root.ChildNodes;
                if (xnl.Count > 7)
                {
                    new LoggEx().Info("微信支付->收到支付通知3...");
                    string result_code = (root.SelectSingleNode("result_code")).InnerText; //业务结果	SUCCESS/FAIL
                    string return_code = (root.SelectSingleNode("return_code")).InnerText; //返回状态码
                    string OrderId = (root.SelectSingleNode("out_trade_no")).InnerText; //商户订单号                 
                    string _transaction_id = (root.SelectSingleNode("transaction_id")).InnerText; //微信支付订单号
                    new LoggEx().Info("微信支付->收到支付通知3...," + OrderId + ";result_code:" + result_code + ";return_code:" + return_code + ";transaction_id:" + _transaction_id);
                    int PayResult = 0;
                    if (result_code.ToUpper() == "SUCCESS")
                    {
                        PayResult = 1;
                        new LoggEx().Info("微信支付->支付成功->开始更新订单支付结果...");
                        //更新订单表
                        _WechatRechargeService.UpdateOrderPayStatus(OrderId, PayResult.ToString(), _transaction_id, 0);
                    }
                    else
                    {
                        new LoggEx().Info("微信支付->支付失败...");
                        PayResult = -1;
                        if (QueryOrder(_transaction_id))
                        {
                            PayResult = 1;
                            //更新订单表
                            _WechatRechargeService.UpdateOrderPayStatus(OrderId, PayResult.ToString(), _transaction_id, 0);
                        }
                        else
                        {
                            PayResult = -1;
                            //更新订单表
                            _WechatRechargeService.UpdateOrderPayStatus(OrderId, PayResult.ToString(), _transaction_id, 0);
                        }
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                new LoggEx().Info("微信支付->异常:"+ex.Message);
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>"; //回调失败返回给微信
            }
        }
        /// <summary>
        /// 查询订单支付结果
        /// </summary>
        /// <param name="transaction_id"></param>
        /// <returns></returns>
        bool QueryOrder(string transaction_id)
        {
            return true;
        }
        #endregion

        /// <summary>
        /// 微信退款回调通知
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("RefundCallback")]
        [AllowAnonymous]
        public async Task<ReturnReFundNotifyModel> RefundCallback()
        {
            new Logger().Debug("进入->RefundCallback->:");
            new Logger().Debug("进入->RefundCallback->:"+ HttpContext.Request.Path.ToString());
            try
            {
                using (StreamReader sr = new StreamReader(Request.Body, Encoding.UTF8))
                {

                    string strContent = sr.ReadToEndAsync().Result;
                    new Logger().Debug("收到退款通知->解密前:" + strContent);
                    var wxPayNotifyModel = strContent.ToObject<WxPayNotifyModel>();
                    var decryptStr = AesGcmHelper.AesGcmDecrypt(wxPayNotifyModel.resource.associated_data, wxPayNotifyModel.resource.nonce, wxPayNotifyModel.resource.ciphertext, WeChatConfig.APIV3Key);
                    new Logger().Debug("收到退款通知->解密后:" + decryptStr);
                    var _ReturnNotifyModel= decryptStr.ToString().ToObject<ReturnReFundNotifyModel>();
                    if (_ReturnNotifyModel != null)
                    {
                        //更新订单表
                        _WechatRechargeService.UpdateOrderRedfundStatus(_ReturnNotifyModel);
                    }
                    return _ReturnNotifyModel;
                }
            }
            catch (Exception e)
            {
                new Logger().Error("收到退款通知->异常:" + e.Message);
                throw;
            }

        }
        
    }
}
